from flask import json

from common.public import *
from orm.model import QuestionBank, db
from peewee import fn
from view.baseview import BaseView


class QuestionBankView(BaseView):

    def __init__(self):
        pass
    @db.atomic()
    def checkQuestionBank(self, params):
        """
        检查题库
        """
        result = []
        where_condition = True   
        if params["tiMu"]:
            where_condition = where_condition & (QuestionBank.ti_mu == params["tiMu"])
                      
        rows = QuestionBank.select().where(where_condition).order_by(QuestionBank.update_time.desc())
        total = rows.count()
        if params["action"] == "edit":
            for row in rows:
                if row.id != params["id"]:
                    return super().resultSet(500, "存在重复题目", [])
        elif params["action"] == "add":
            if total > 0:
                return super().resultSet(500, "存在重复题目", []) 
        return super().resultSet(200, "不重复", [])

    @db.atomic()
    def addQuestionBank(self, params):
        """
        添加题库
        """
        strright = ""
        for row in params["rightchoose"]:
            strright += ",'" + row["value"] + "'"
        strright = strright.replace(",", "", 1)
        params["xuanXiang"] = str(params["xuanXiang"]).replace("'", "\"").replace(r"\n", "")
        res = self.checkQuestionBank(params)
        if res['code'] == 500:
            return super().resultSet(500, "存在重复题目,更新失败", [])
        question_bank = QuestionBank.create(
            stype = params["stype"],
            type = params["type"],
            question_type = params["questionType"],
            ti_mu = params["tiMu"],
            rightchoose = strright,
            xuan_xiang = params["xuanXiang"],
            add_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
            update_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
        )
        return super().resultSet(200, "添加成功", [])
        raise Exception("添加失败")

    @db.atomic()
    def updateQuestionBank(self, params):
        """
        更新题库
        """
        strright = ""
        for row in params["rightchoose"]:
            strright += ",'" + row["value"] + "'"
        strright = strright.replace(",", "", 1)
        params["xuanXiang"] = str(params["xuanXiang"]).replace("'", "\"").replace(r"\n", "")
        res = self.checkQuestionBank(params)
        if res['code'] == 500:
            return super().resultSet(500, "存在重复题目,更新失败", [])
        question_bank = QuestionBank.get(QuestionBank.id == params["id"])
        question_bank.type = params["type"]
        question_bank.stype = params["stype"]
        question_bank.question_type = params["questionType"]
        question_bank.ti_mu = params["tiMu"]
        question_bank.rightchoose = strright  # params["rightchoose"]
        question_bank.xuan_xiang = params["xuanXiang"]
        question_bank.save()
        return super().resultSet(200, "更新成功", [])
        raise Exception("更新失败")
    
    def queryQuestionBank(self, params):
        """根据条件取得，params：条件参数"""
        result = []
        where_condition = True
        # print(time.localtime())
        # print(time.strftime("%Y-%m-%d", time.localtime()))
        if params["stype"]:
            where_condition = where_condition & (QuestionBank.stype.in_(params["stype"]))
        if params["type"]:
            where_condition = where_condition & (QuestionBank.type == params["type"])
        if params["questionType"]:
            where_condition = where_condition & (QuestionBank.question_type == params["questionType"])
        if params["tiMu"]:
            likestr = "%" + params["tiMu"] + "%"
            where_condition = (QuestionBank.ti_mu ** likestr)
        if params["addTime"]:
            where_condition = where_condition & ((QuestionBank.add_time >= params["addTime"][0] + " 00:00:00") \
                                               & (QuestionBank.add_time <= params["addTime"][1] + " 23:59:59"))
        if params["updateTime"]:
            where_condition = where_condition & ((QuestionBank.update_time >= params["updateTime"][0] + " 00:00:00") \
                                               & (QuestionBank.update_time <= params["updateTime"][1] + " 23:59:59"))
       
        total = QuestionBank.select().where(where_condition).count()
        rows = QuestionBank.select().where(where_condition).order_by(QuestionBank.update_time.desc()).paginate(int(params["pageNo"]), int(params["pagesize"]))
        for row in rows:
            if row.add_time != None:
                row.add_time = time.strftime("%Y-%m-%d", time.strptime(str(row.add_time), "%Y-%m-%d %H:%M:%S"))
            if row.update_time != None:
                row.update_time = time.strftime("%Y-%m-%d", time.strptime(str(row.update_time), "%Y-%m-%d %H:%M:%S"))
            data = {
                "id":row.id,
                "type":row.type,
                "stype":row.stype,
                "questionType":row.question_type,
                "tiMu":row.ti_mu,
                "rightchoose":row.rightchoose,
                "xuanXiang":json.loads(row.xuan_xiang),
                "addTime":row.add_time,
                "updateTime":row.update_time,
             }
            result.append(data)
        return super().resultSet(200, "", result, total = total)

    def initTestType(self):
        """取得题库大分类"""
        result = []
        rows = QuestionBank.select(fn.Distinct(QuestionBank.type)).where(QuestionBank.type.is_null(False)).order_by(QuestionBank.type)
        for row in rows:
            result.append(row.type)
        return super().resultSet(200, "题库大分类取得成功", result)

    def initTestSubType(self,type):
        """取得题库小分类"""
        result = []
        rows = QuestionBank.select(fn.Distinct(QuestionBank.stype)).where((QuestionBank.type == type) & (QuestionBank.stype.is_null(False))).order_by(QuestionBank.type)
        for row in rows:
            result.append(row.stype)
        return super().resultSet(200, "题库小分类取得成功", result)